const t = getApp()
//var bmap = require('../lib/bmap-wx.min.js');
var amapFile = require('../lib/amap-wx.130.js');//如：..­/..­/libs/amap-wx.js//38.91459/121.618622
Page({
  data: {
    iconsUrl:t.globalData.iconsUrl,
    list:[],
    total:0,
    page: '1',
    pages: '',
    size: 10,
    swiper:[],
    lat:'',
    lon:'',
    loading:true,
    baiduAK:'FNKrsLmAYvpX9vRs8aaCga0uFXfWfbQN',
    gaodeAK:'f69e9aff1c198bc1f72a6877f027cb4a',
    hefengAK:'4760cdb3f52a407e9ef96e9f2ee69b22',
    weatherarr: '',
    province:'',
    city:'',
    today:[],
    tomorrow:[],
    dayAfterTomorrow:[],
    more:false,
    canmore:false,
    navHeight:t.globalData.navHeight,
    title:'美途洗车',
// 获取手机号弹窗参数
    show: false,
    duration: 300, //动画时长，单位毫秒
    position: 'bottom',
    round: true,  //是否显示圆角
    overlay: true, //是否显示遮罩层
    customStyle: '',//自定义弹出层样式
    overlayStyle: '' //自定义遮罩层样式
  },
  onLoad(e){
    this.get_weather();
  },
  // 显示电话登录的弹窗
  showTelLogin(){
    let that = this
    that.setData({show: true})
    // 隐藏底部 tabbar
    wx.hideTabBar({
      animation: false, // 是否需要动画效果，默认为 false
      success: function () {
        console.log('TabBar has been hidden successfully!');
        that.setData({show: true})
      },
      fail: function (err) {
        console.error('Failed to hide TabBar:', err);
      }
    });
  },
  // 手机号 暂不登录按钮
  exit() {
    this.setData({show: false})
    // 显示底部tabbar
    wx.showTabBar({
      animation: false, // 是否需要动画效果，默认为 false
      success: function () {
        console.log('TabBar has been hidden successfully!');
      },
      fail: function (err) {
        console.error('Failed to hide TabBar:', err);
      }
    });
  },
  //电话登录
  getPhoneNumber(e){
    const that = this,
      iv = e.detail.iv,
      da = e.detail.encryptedData;
    if (!e.detail.encryptedData) return wx.showToast({ title: '授权失败,请重新授权！',icon:'none'})
    // 请求接口
    wx.login({
      success(e){
        console.log(e);
        wx.showLoading({
          title: '请稍后',
        })
        t.request('/login/getPhoneNumber',{code: e.code,iv:iv,encryptedData:da},function(event){
          wx.hideLoading({})
          if (event.code!==200) return wx.showToast({ title: event.msg,icon:'none' })
          if (event.code==200) {
            wx.setStorageSync('tel', event.result.phoneNumber)
            t.globalData.show_tel_login =false
            that.exit()
          }
        })
      }
    })
  },
  onShow(e){
    var that = this
    wx.login({
      success: res => {
        t.request('/login',{code:res.code},function(r){
          t.globalData.token = r.result.token;
          wx.setStorageSync('token', r.result.token);
          wx.getLocation({
            type: 'wgs84',
            success (res) {
              console.log(res);
              that.setData({
                lat:res.latitude,
                lon:res.longitude
              })
              that.get_list()
            },
            fail: function (res) {
              console.info('ready getLocation fail=' + JSON.stringify(res))
             }
          })
          // wx.setStorageSync('userinfo', r.result.userInfo)
          if(r.result.userInfo.get_phone == 0){
            t.globalData.show_tel_login = true;
            // that.showTelLogin(); //电话登录违规
            // t.show_login()
          }else{
            wx.setStorageSync('tel', r.result.userInfo.phone)
            t.globalData.show_tel_login = false;
          }

          // if(r.result.userInfo.cars == 0){
          //   // t.show_login()
          // }else{
          //   t.globalData.show_login = false;
          // }
        })
      }
    })
    this.get_swiper()
  },
  /*
  '有风':'code1',
      '平静':'code1',
      '微风':'code1',
      '和风':'code1',
      '清风':'code1',
      '强风/劲风':'code1',
      '疾风':'code1',
      '大风':'code1',
      '烈风':'code1',
      '风暴':'code1',
      '狂爆风':'code1',
      '飓风':'code1',
      '热带风暴':'code1',
      '龙卷风':'code1',
  */
  get_weather(){
    var date={
      '晴':'100',//150
      '少云':'102',//152
      '晴间多云':'103',//153  
      '多云':'101',//151
      '阴':'104',
      '霾':'502',
      '中度霾':'511',
      '重度霾':'512',
      '严重霾':'513',
      '阵雨':'300',
      '雷阵雨':'302',
      '雷阵雨并伴有冰雹':'304',
      '小雨':'305',
      '中雨':'306',
      '大雨':'307',
      '暴雨':'310',
      '大暴雨':'311',
      '特大暴雨':'312',
      '强阵雨':'301',
      '强雷阵雨':'303',
      '极端降雨':'308',
      '毛毛雨/细雨':'309',
      '雨':'399',
      '小雨-中雨':'314',
      '中雨-大雨':'315',
      '大雨-暴雨':'316',
      '暴雨-大暴雨':'317',
      '大暴雨-特大暴雨':'318',
      '雨雪天气':'405',
      '雨夹雪':'404',
      '阵雨夹雪':'456',
      '冻雨':'313',
      '雪':'499',
      '阵雪':'457',
      '小雪':'400',
      '中雪':'401',
      '大雪':'402',
      '暴雪':'403',
      '小雪-中雪':'408',
      '中雪-大雪':'409',
      '大雪-暴雪':'410',
      '浮尘':'504',
      '扬沙':'503',
      '沙尘暴':'507',
      '强沙尘暴':'508',
      '雾':'501',
      '浓雾':'509',
      '强浓雾':'510',
      '轻雾':'500',
      '大雾':'514',
      '特强浓雾':'510',
      '热':'900',
      '冷':'901',
      '未知':'999',
    }
    var that = this
    var myAmapFun = new amapFile.AMapWX({key:that.data.gaodeAK});
    myAmapFun.getWeather({
      type:'forecast',//表示获取的是预报信息 默认live（实时天气）
      success: function(data){
        //console.log(data)
        //成功回调
        var weatherarr = new Array(3);
        for(var i = 0; i < 3; i++){
          weatherarr[i] = data.forecast.casts[i];//获取后三天预报信息 今日的不保存
          weatherarr[i].icon=date[weatherarr[i].dayweather];
          weatherarr[i].icon1=date[weatherarr[i].nightweather];
        }
        that.setData({
          province:data.forecast.province,
          city:data.forecast.city,
          weatherarr:weatherarr,
          tomorrow:weatherarr[1],
          dayAfterTomorrow:weatherarr[2],
        })
        console.log(weatherarr);
      },
      fail: function(info){
        //失败回调
        console.log(info)
      }
    });
    myAmapFun.getWeather({
      type:'live',//表示获取的是预报信息 默认live（实时天气）
      success: function(data){
        console.log(data.liveData);
        var todayarr ={};
        todayarr['temperature']=data.liveData.temperature;
        todayarr['weather']=data.liveData.weather;
        todayarr['icon']=date[data.liveData.weather];
        console.log(todayarr);
        that.setData({
          today:todayarr,
        })
        //成功回调
      },
      fail: function(info){
        //失败回调
        console.log(info)
      }
    });
  },
  onRefresh(){
    //在当前页面显示导航条加载动画
    wx.showNavigationBarLoading(); 
    //显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框
    this.setData({
      page:1,
    })
    this.get_list2();
  },
  onPullDownRefresh: function () {
    //调用刷新时将执行的方法
    this.onRefresh();
    setTimeout(function () {
      // 不加这个方法真机下拉会一直处于刷新状态，无法复位
      wx.stopPullDownRefresh()
    }, 1000)
  },
  onReachBottom: function () {
    
    var that = this
    
    //如果页码大于等于总页数，则做出提示
    if (that.data.page > that.data.pages) {

    }else{
      //页面加载中给出提示
      /*
    wx.showToast({
        title: '正在加载中....',
        icon: "loading"
    })*/
    that.setData({
      canmore:true
    })
      var o = {
        lat:this.data.lat || 0,
        lng:this.data.lon || 0,
        page: this.data.page,
        size: this.data.size
      }
      t.request('/store/listX',o,function(e){
        wx.hideLoading({
          success: (res) => {},
        })
          //返回数据后赋值、循环
          var arr = e.result.list;
          arr.forEach(function (v, k) {
              //将每一个值追加到list数组中
              v.distance = v.distance.toFixed(1)
              that.data.list.push(v)
          });
          //替换掉list，page（page值为返回的值）
          that.setData({
              list: that.data.list,
              page: e.result.page,
              canmore:false
          })
      })
    }
  },
  get_list2(e){
    var that = this
    that.setData({
      list: [],
    }) 
    console.log(that.data.list);
    var o = {
      lat:this.data.lat || 0,
      lng:this.data.lon || 0,
      page: 1,
      size: this.data.size
    }
    t.request('/store/lsst',o,function(e){
      wx.hideLoading({
        success: (res) => {},
      })

      //返回数据后赋值、循环
      var arr = e.result.list;
      arr.forEach(function (v, k) {
          //将每一个值追加到list数组中
          v.distance = v.distance.toFixed(1)
          that.data.list.push(v)
      });
      //替换掉list，page，pages（后边两个值均为返回的值）
      that.setData({
          list: that.data.list,
          page: e.result.page,
          pages: e.result.pages,
          total:e.result.total,
      })    
    })
  },
  get_list(e){
    var that = this
    var o = {
      lat:this.data.lat || 0,
      lng:this.data.lon || 0,
      page: this.data.page,
      size: this.data.size
    }
    t.request('/store/lsst',o,function(e){
      wx.hideLoading({
        success: (res) => {},
      })

      //返回数据后赋值、循环
      var arr = e.result.list;
      arr.forEach(function (v, k) {
          //将每一个值追加到list数组中
          v.distance = v.distance.toFixed(1)
          that.data.list.push(v)
      });
      //替换掉list，page，pages（后边两个值均为返回的值）
      that.setData({
          list: that.data.list,
          pages: e.result.pages,
          total:e.result.total,
          page: e.result.page,
      })    
      
    })

  },
  get_swiper(e){
    var that = this
    t.request('/banner/getList',{},function(e){
      console.log(e);
      if(e.code!==200)return wx.showToast({ title:e.msg,icon:"none" })
      if (e.result.list.length<=0) return
      let list = e.result.list
      let swiper = []
      list.forEach(ele => {
        swiper.push(ele.media_url)
      });
      that.setData({
        swiper
      })
    })
  },
  to_page(e){
    if (t.globalData.show_login) {t.show_login();return;}
    var page 
    switch (e.currentTarget.dataset.page) {
      case 'invest':
        page = '/pages/personCenter/chooseStore/invest/invest?store_id=' + e.currentTarget.dataset.store_id
        break;
      case 'store':
        page = '/pages/store/store?store_id=' + e.currentTarget.dataset.store_id + '&dis=' + e.currentTarget.dataset.dis
        break;
      default:
        break;
    }
    wx.navigateTo({
      url: page,
    })
  },
  navigate(){
    wx.navigateTo({
      url: '/pages/personCenter/myCar/myCar',
    })
  },
  to_map(e){
    var list=this.data.list
    for (let i = 0; i < list.length; i++) {
      if (list[i].b_id == e.currentTarget.dataset.b_id) {
        wx.getLocation({
          type: 'wgs84', 
          success: function (res) {
            wx.openLocation({
              latitude: +list[i].lat,
              longitude: +list[i].lng,
              name: list[i].title,
              address: list[i].address
            })
          }
        })
        return
      }
    }
  },
  search(e){
    var that = this
    console.log(e);
    t.request('/store/serch',{keyword:e.detail.value?e.detail.value:''},function(e){
      console.log(e);
      if(e.code!==200)return wx.showToast({ title:e.msg,icon:"none" })
      if(e.result.total<=0){
        wx.showToast({
          title: '未查找到相关结果',
          icon:'none'
        })
      }
    })
  },
  onShareAppMessage(e){
    
  },
  show_more(){
    this.setData({
      more:true,
      canmore:false
    })
    this.get_list();
  },
  show_fake(e){
    wx.showToast({
      title: '敬请期待',
      icon:'none'
    })
  },
  get_location(){
    var that = this
    wx.login({
      success: res => {
        t.request('/login',{code:res.code},function(r){
          t.globalData.token = r.result.token;
          wx.setStorageSync('token', r.result.token);
          wx.getLocation({
            type: 'wgs84',
            success (res) {
              console.log(res);
              that.setData({
                lat:res.latitude,
                lon:res.longitude
              })
              that.get_list()
            }
          })
          // wx.setStorageSync('userinfo', r.result.userInfo)
          if(r.result.userInfo.cars == 0){
            // t.show_login()
          }else{
            t.globalData.show_login = false;
          }
        })
      }
    })
    this.get_swiper()
  },
  goto(){
    /*wx.navigateTo({
      url: '/pages/code_start/code_start',
    })*/
    wx.navigateTo({
      url: '/pages/settle_accounts/settle_accounts',
    })
    /*wx.navigateTo({
      url: '/pages/login/login',
    })*/
  },
  errorFunction(){
    this.setData({
     avatar: '/images/door_back.png'
    }) 
   },
  new_get(){
    var that = this
    wx.getLocation({
      success: res => {
        console.log(res);
      },
      fail: e => {
        console.log(e);
        // 判断用户是否拒绝了授权
        wx.getSetting({
          success: res => {
            if (typeof(res.authSetting['scope.userLocation']) != 'undefined' && !res.authSetting['scope.userLocation']) {
              // 用户拒绝了授权
              wx.showModal({
                title: '提示',
                content: '您拒绝了定位权限，将无法使用XX功能',
                success: res => {
                  if (res.confirm) {
                    // 跳转设置页面
                    wx.openSetting({
                      success: res => {
                        if (res.authSetting['scope.userLocation']) {
                          // 授权成功，重新定位
                          wx.login({
                            success: res => {
                              t.request('/login',{code:res.code},function(r){
                                t.globalData.token = r.result.token;
                                wx.setStorageSync('token', r.result.token);
                                wx.getLocation({
                                  type: 'wgs84',
                                  success (res) {
                                    console.log(res);
                                    that.setData({
                                      lat:res.latitude,
                                      lon:res.longitude
                                    })
                                    that.get_list();
                                    that.get_weather();
                                  }
                                })
                                // wx.setStorageSync('userinfo', r.result.userInfo)
                                if(r.result.userInfo.cars == 0){
                                  // t.show_login()
                                }else{
                                  t.globalData.show_login = false;
                                }
                              })
                            }
                          })
                          this.get_swiper()
                        } else {
                          // 没有允许定位权限
                          wx.showToast({
                            title: '您拒绝了定位权限，将无法使用XX功能',
                            icon: 'none'
                          });
                        }
                      }
                    });
                  }
                }
              });
            }
          }
        });
      }
    });
  }
})
